package com.idcard.huashi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.zysoft.function.ApiUtil;
import com.zysoft.function.Stroage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
 * Author : wmf
 * CreationTime : 2019/08/25
 * Description: 班组操作
 */
public class TeamFragment  extends Activity {

    private TextView offline_data_submit;//离线提交数据
    private TextView update_data;//更新本地数据
    private TextView log_exit;//退出登录
    private TextView btn_center;//取消Alert
    private TextView Switch_project;//项目切换
    private TextView Staff_exit;//人员退场
    private TextView data_entry;//数据录入
    private TextView depart_data;//班组部门
    private TextView Power_off;//设备断电
    private TextView add_team;//添加班组
    private Spinner spinnerType;
    private ListView team_list;
    private Alert alert;
    private ApiUtil apiUtil;
    private Stroage stroage;
    private ArrayList<String> InfoData;
    private ArrayList<String> InfoCode;
    private ArrayList<String> workTeamName;
    private ArrayList<String> workTeamCode;
    private ArrayList<String> workerType;
    private ArrayList<String> workerCode;
    private ArrayAdapter<String> adapter;
    private String workTypeId = null;//工种id
    private String masterName = null;//班组名称
    private String workTeamId = null;//作业队id
    private String worlkName = null;//作业对名称

    public static final int SUCCEED = 0;
    public static final int FAILE = 1;
    public static final int DETE_SUCCEED =2;
    public static final int DETE_FAILE =3;
    public static final int TYPESUCCEED = 4;
    public static final int TYPEFAILE =5;
    private int num;

    private View view;
    private Context mCtx;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 使用自定义标题栏;
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        // TODO Auto-generated method stub
        mCtx = this;
        alert = new Alert();
        apiUtil= new ApiUtil();
        stroage = new Stroage();
        InfoData = new ArrayList<String>();
        InfoCode = new ArrayList<String>();
        workTeamName = new ArrayList<String>();
        workTeamCode = new ArrayList<String>();
        workerType = new ArrayList<String>();
        workerCode = new ArrayList<String>();
        setContentView(R.layout.activity_team);
        team_list = findViewById(R.id.team_list);
        View show = findViewById(R.id.img_btn);
        View back = findViewById(R.id.img_back);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mCtx,IdcardFragment.class);
                startActivity(intent);
                finish();
            }
        });
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alert.ShowAlert();
            }
        });
        apiUtil.ShowLoading("加载中...",mCtx);
        Ajax();
    }
    private void TypeShow(String data){
        try {
            workerCode = new ArrayList<String>();
            workerType = new ArrayList<String>();
            JSONObject js = new JSONObject(data);
            for (int i =0;i<js.getJSONArray("workerType").length();i++){
                workerCode.add(js.getJSONArray("workerType").getJSONObject(i).getString("value"));
                workerType.add(js.getJSONArray("workerType").getJSONObject(i).getString("text"));
            }
            alert.ShowAdd();
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("zysoft","解析失败");
            apiUtil.ShowToast("数据解析失败");
        }
        apiUtil.HideLoading();
    }
    public void initView(){
        add_team = findViewById(R.id.add_team);
        add_team.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("zysoft","添加班组");
                if(workerType.size()==0){
                    apiUtil.ShowLoading("请稍后...",mCtx);
                    Type();
                }else {
                    alert.ShowAdd();
                }
            }
        });
       adapter = new ArrayAdapter<String>(mCtx, R.layout.activity_team_item, R.id.team_list_item, InfoData);
        team_list.setAdapter(adapter);
//        team_list.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                num = i;
//                Log.e("zysoft",team_list.getItemAtPosition(i).toString());
//                alert.ConfirmAlert(team_list.getItemAtPosition(i).toString());
//            }
//        });
    }
    private void Ajax(){
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(10,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("projectCode",stroage.getCode(mCtx).toString())
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.DepartTeam)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("zysoft", "responseCode" +"   " + response.code() + "responseMessage" + response.message());
                mHandler.sendMessage(mHandler.obtainMessage(SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                if(e instanceof SocketTimeoutException){
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "请求超时"));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "连接异常"));
                }
            }
        });

    }
    private void Type(){
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(10,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.DictionaryItem)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("zysoft", "responseCode" +"   " + response.code() + "responseMessage" + response.message());
                mHandler.sendMessage(mHandler.obtainMessage(TYPESUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("zysoft",e.getMessage());
                if(e instanceof SocketTimeoutException){
                    mHandler.sendMessage(mHandler.obtainMessage(TYPEFAILE, "请求超时"));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(TYPEFAILE, "连接异常"));
                }
            }
        });

    }
    public class Alert implements View.OnClickListener {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View show = inflater.inflate(R.layout.show_dialog, null);
        View add = inflater.inflate(R.layout.add_show, null);
        View confirm = inflater.inflate(R.layout.confirm, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
        Dialog dialog = builder.create();

        public void ShowAdd(){
             final EditText editText =  add.findViewById(R.id.add_team_name);
             final TextView team_center_add =  add.findViewById(R.id.team_center_add);
             final Spinner spinner = add.findViewById(R.id.spinner);//作业队
            spinnerType =  add.findViewById(R.id.spinner_Type);//工种
            dialog.show();
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager windowManager =getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            lp.width = display.getWidth()/4*3;
            dialog.getWindow().setAttributes(lp);
            dialog.getWindow().setGravity(Gravity.CENTER_VERTICAL);//可以设置显示的位置
            dialog.getWindow().setContentView(add);//自定义布局应该在这里添加，要在dialog.show()的后面
            //作业队
            Log.e("zysoft", String.valueOf(workTeamName));
            final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mCtx,android.R.layout.simple_spinner_item,workTeamName);
            adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
            spinner.setAdapter(adapter);
            //工种
            ArrayAdapter<String> adapterType = new ArrayAdapter<String>(mCtx,android.R.layout.simple_spinner_item,workerType);
            adapterType.setDropDownViewResource(android.R.layout.select_dialog_item);
            spinnerType.setAdapter(adapterType);
            //选择作业队
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    workTeamId = workTeamCode.get(i);
                    worlkName = spinner.getItemAtPosition(i).toString();
                    Log.e("hello", String.valueOf(spinner.getItemAtPosition(i)));
                    Log.e("zysoft",workTeamCode.toString());
                }
                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            spinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    workTypeId = workerCode.get(i);
                    Log.e("zysoft",workerCode.get(i));
                }
                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });
            editText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);//弹出软件盘
                }
            });
            //确定添加班组
            team_center_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    masterName = editText.getText().toString().trim();
                    if(TextUtils.isEmpty(masterName)){
                        apiUtil.ShowToast("班组名称不能为空");
                        return;
                    }
                    if(TextUtils.isEmpty(workTypeId)){
                        apiUtil.ShowToast("请选择工种");
                        return;
                    }
                    if(TextUtils.isEmpty(workTeamId)){
                        apiUtil.ShowToast("请选择作业队");
                        return;
                    }
                    HideAlert();
                    apiUtil.ShowLoading("添加中...",mCtx);
                    addTeam();
                }
            });
        }
        //删除
        public void ConfirmAlert(String text){
             final TextView textConform = (TextView) confirm.findViewById(R.id.textConform);
            textConform.setText("你确定删除"+ text +"？");
            dialog.show();
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            lp.width = display.getWidth()/4*3;
            dialog.getWindow().setAttributes(lp);
            dialog.getWindow().setGravity(Gravity.CENTER_VERTICAL);//可以设置显示的位置
            dialog.getWindow().setContentView(confirm);//自定义布局应该在这里添加，要在dialog.show()的后面
            //取消
            confirm.findViewById(R.id.center_btn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HideAlert();
                }
            });
            //删除
            confirm.findViewById(R.id.confirm_btn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HideAlert();
                    apiUtil.ShowLoading("删除中...",mCtx);
                    //delete();
                }
            });
        }
        public void ShowAlert(){
            dialog.show();
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager windowManager =getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            lp.width = display.getWidth();
            dialog.getWindow().setAttributes(lp);
            dialog.getWindow().setGravity(Gravity.BOTTOM);//可以设置显示的位置
            dialog.getWindow().setContentView(show);//自定义布局应该在这里添加，要在dialog.show()的后面

            offline_data_submit =  show.findViewById(R.id.offline_data_submit);//离线提交
            update_data =  show.findViewById(R.id.update_data);//更新本地数据
            Switch_project =  show.findViewById(R.id.Switch_project);//切换项目
            Staff_exit =  show.findViewById(R.id.Staff_exit);//人员退场
            log_exit = show.findViewById(R.id.log_exit);//退出登录
            data_entry = show.findViewById(R.id.data_entry);//进场数据录入
            depart_data = show.findViewById(R.id.depart_data);//班组部门
            Power_off = show.findViewById(R.id.Power_off);
            btn_center =  show.findViewById(R.id.btn_center);//取消
            Power_off.setVisibility(View.GONE);
            depart_data.setVisibility(View.GONE);
            offline_data_submit.setVisibility(View.GONE);
            update_data.setVisibility(View.GONE);
            //监听事件
            Staff_exit.setOnClickListener(this);
            data_entry.setOnClickListener(this);
            Switch_project.setOnClickListener(this);
            log_exit.setOnClickListener(this);
            Power_off.setOnClickListener(this);
            btn_center.setOnClickListener(this);

        }
        public void HideAlert(){
            dialog.dismiss();
        }
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.Staff_exit:
                    HideAlert();
                    Intent intent = new Intent(mCtx,StaffExitFragment.class);
                    startActivity(intent);
                    finish();
                    break;
                case R.id.data_entry:
                    HideAlert();
                    Intent per = new Intent(mCtx,IdcardFragment.class);
                    startActivity(per);
                    finish();
                    break;
                case R.id.Switch_project:
                    HideAlert();
                    Intent CHE = new Intent(mCtx,ProjectFragment.class);
                    startActivity(CHE);
                    finish();
                    break;
                case R.id.log_exit:
                    HideAlert();
                    Intent exit = new Intent(mCtx,MainActivity.class);
                    startActivity(exit);
                    finish();
                    break;
                case R.id.Power_off:
                    HideAlert();
                    break;
                case R.id.btn_center:
                    HideAlert();
                    break;

            }
        }
    }
    @SuppressLint("HandlerLeak")
    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCEED: {
                  try {
						JSONObject json = new JSONObject(msg.obj.toString());
						if(json.has("code") && (json.getInt("code") == 200)){
							Team(json.getJSONObject("data").toString());
						}else {
						    apiUtil.ShowToast(json.getString("msg"));
                        }
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("zysoft","解析失败");
						apiUtil.ShowToast("数据解析失败");
					}
					apiUtil.HideLoading();
                    break;
                }
                case FAILE:{
                    Log.e("zysoft", msg.obj.toString());
                    apiUtil.HideLoading();
                    apiUtil.ShowToast(msg.obj.toString());
                    break;
                }
                case DETE_SUCCEED:{
//                    InfoData.remove(num);
//                    adapter.notifyDataSetChanged();
//                    team_list.invalidate();
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.has("code") && (json.getInt("code") == 200)){
                            apiUtil.ShowToast("添加成功");
                            InfoData.add(worlkName+"--"+masterName);
                            adapter.notifyDataSetChanged();
                            team_list.invalidate();
                            workTeamId = null;
                            workTypeId = null;
                            masterName = null;
//                            apiUtil.ShowLoading("加载中...",mCtx);
//                            Ajax();

                        }else {
                            apiUtil.ShowToast(json.getString("msg"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("zysoft","解析失败");
                        apiUtil.ShowToast("数据解析失败");
                    }
                    apiUtil.HideLoading();
                    break;
                }
                case DETE_FAILE:{
                    apiUtil.HideLoading();
                    apiUtil.ShowToast((String)msg.obj);
                    break;
                }
                case TYPESUCCEED:{
                    try {
                        workerCode = new ArrayList<String>();
                        workerType = new ArrayList<String>();
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.has("code") && (json.getInt("code") == 200)){
                            TypeShow(json.getJSONObject("data").toString());
                        }else {
                            apiUtil.ShowToast(json.getString("msg"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("zysoft","解析失败");
                        apiUtil.ShowToast("数据解析失败");
                    }
                    apiUtil.HideLoading();
                    break;
                }
                case TYPEFAILE:{
                    apiUtil.HideLoading();
                    apiUtil.ShowToast((String)msg.obj);
                    break;
                }
            }
        }
    };
    private void Team(String data){
        try {
            JSONObject js = new JSONObject(data);
            JSONArray InfoArry = js.getJSONArray("children");
            InfoCode = new ArrayList<String>();
            InfoData = new ArrayList<String>();
            workTeamName = new ArrayList<String>();//作业队
            workTeamCode = new ArrayList<String>();
            if(InfoArry.length() == 0){
                apiUtil.HideLoading();
                apiUtil.ShowToast("暂无数据");
                return;
            }
            for(int i=0;i<InfoArry.length();i++){//项目下面的分包商
                JSONArray work = InfoArry.getJSONObject(i).getJSONArray("children");
                for(int j =0;j<work.length();j++){//某一分包商下面的作业队
                    workTeamName.add(work.getJSONObject(j).getString("name"));//作业队
                    workTeamCode.add(work.getJSONObject(j).getString("id"));
                    JSONArray team = work.getJSONObject(j).getJSONArray("children");
                    for(int k = 0;k<team.length();k++){//某一作业队下面的数组
                        InfoData.add(work.getJSONObject(j).getString("name")+"——"+team.getJSONObject(k).optString("name"));
                        InfoCode.add(team.getJSONObject(k).optString("id"));
                    }
                }
            }
            initView();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void addTeam() {
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(10,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("workType",workTypeId )
                .add("masterName",masterName )
                .add("workTeamId",workTeamId)
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.teamAdd)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("zysoft", "responseCode" + "   " + response.code() + "responseMessage" + response.message());
                mHandler.sendMessage(mHandler.obtainMessage(DETE_SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                if (e instanceof SocketTimeoutException) {
                    mHandler.sendMessage(mHandler.obtainMessage(DETE_FAILE, "请求超时"));
                } else {
                    mHandler.sendMessage(mHandler.obtainMessage(DETE_FAILE, "连接异常"));
                }
                Log.e("zysoft", "onFailure: " + e.getMessage());
            }
        });
    }
}
